/**
 *
 * jcrt and its source-code is licensed under the LGPL.
 * You may copy, adapt, and redistribute this file for commercial or non-commercial use.
 * When copying, adapting, or redistributing this document in keeping with the guidelines above,
 * you are required to provide proper attribution to obinary.
 * If you reproduce or distribute the document without making any substantive modifications to its content,
 * please use the following attribution line:
 *
 * Copyright 2007 Atjava.com Ltd. (http://www.atjava.com) All rights reserved.
 *
 */
package com.atjava.jcrweb.servlet;

import java.io.IOException;
import java.io.InputStream;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.atjava.jcrweb.info.FileInfo;
import com.atjava.jcrweb.manager.FileManager;
/**
 * 
 * 
 * @author biggie
 * @version $Revision: 1.3 $ $Date: 2008/07/17 02:07:39 $
 */
public class DownloadFlexServlet extends HttpServlet {

	/**
	 * serialVersionUID
	 */
	private static final long serialVersionUID = 1L;

    public void doGet(HttpServletRequest request, HttpServletResponse response)
	    throws IOException, ServletException {
    	process(request, response);
	}
	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
	    throws IOException, ServletException {
		process(request, response);
	}

	public String process(HttpServletRequest request,HttpServletResponse response)
			throws IOException, ServletException{
		ServletOutputStream os = null;
		try {
			String path = request.getParameter("path");
			
			FileManager manager = FileManager.getInstance();
    	    String id = request.getParameter("fileId");
    	    FileInfo info = manager.getFile(path,Long.parseLong(id));
    	    if(info == null){
    	    	throw new IOException("The File Cannot Be Download !");
    	    }
    		response.setContentType("bin");
    		response.setHeader("Content-Disposition", "attachment; filename="+info.getFileName());
    		os = response.getOutputStream();
    		InputStream in = info.getInputStream();
    		byte[] data = new byte[1024];
    		int temp = -1;
    		while((temp=in.read(data))!= -1){
    			os.write(data,0,temp);
    			os.flush();
    		}
		} catch (Exception e) {
			throw new IOException("The File Cannot Be Download !" + e.getMessage());
		}
		return null;
	}
}
